const express = require('express');
const mysql = require('mysql');
const bcrypt = require('bcrypt')
const saltRounds = 10
const db = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'rootroot',
    database: 'jd_mysql'
});
module.exports = () => {
    const route = express.Router();
    const getHomeStr = `SELECT product_id,product_name,product_price,product_img_url,product_uprice FROM product`;
    const getCateNames = `SELECT * FROM category ORDER BY category_id desc`;
    //get homePage datas
    route.get('/home', (req, res) => {
        getHomeDatas(getHomeStr, res);
    });

    function getHomeDatas(getHomeStr, res) {
        db.query(getHomeStr, (err, data) => {
            if (err) {
                console.log(err);
                res.send({msg: '获取信息失败请联系管理员', status: 507}).end();
            } else {
                res.send({bussdata: data,msg:'获取成功', status: 1});
            }
        });
    }

    route.get('/category', (req, res) => {
        getCateNamesDatas(getCateNames, res);
    });

    function getCateNamesDatas(getCateNames, res) {
        db.query(getCateNames, (err, data) => {
            if (err) {
                console.log(err);
                res.status(500).send('database err').end();
            } else {
                if (data.length == 0) {
                    res.status(500).send('no datas').end();
                } else {
                    res.send(data);
                }
            }
        });
    };
    route.get('/categorygoods', (req, res) => {
        let mId = req.query.mId;
        const sql = `select * from product,category where product.category_id=category.category_id and category.category_id='${mId}'`;
        getCateGoods(sql, res);
    });

    function getCateGoods(sql, res) {
        db.query(sql, (err, data) => {
        if (err) {
                console.log(err);
                res.send({msg:'请联系管理员',status:506}).end();
            } else {
        res.send({databuss: data, msg: '获取成功', status: 1});
            }
        });
    }
    route.get('/categorygoodsSum', (req, res) => {
        const sql = `select * from category`
        db.query(sql,(err, data) => {
            if (err) return res.send({msg:'请联系管理员', status:506})
            res.send({bussdata: data, status:1, msg: '获取数据成功'})
        })
    })
    route.get('/detail', (req, res) => {
        let produId = req.query.mId;
        const imagesStr = `select image_url from product_image where product_id='${produId}'`;
        const productStr = `select * from product where product_id='${produId}'`;
            let arr = []
            db.query(imagesStr, (err, imgDatas) => {
            if (err) {
                console.error(err);
                res.send({msg: '请联系管理员', status: 505}).end();
            } else {
                arr.push(imgDatas)
                db.query(productStr, (err, data) => {
                    if (err) {
                        console.error(err);
                        res.send({msg:'请联系管理员', status: 506}).end();
                    } else {
                        arr.push(data)
                        res.send({bussdata: arr, msg:'获取成功', status: 1});
                    }
                });
            }
        });

    });
    route.get('/cart', (req, res) => {
        let mobj = req.query.uid
        console.log(mobj)
        const cartStr = `SELECT flag,cart_id,user.user_id,product.product_id,product_name,product_uprice,product_img_url,goods_num,product_num,shop_name FROM product,user,goods_cart,shop where product.product_id=goods_cart.product_id and user.user_id=${mobj} and shop.shop_id = product.shop_id`;
        db.query(cartStr, (err, data) => {
            if (err) {
                console.log(err);
                res.send({msg:'请联系管理员', status:506}).end();
            } else {
                res.send({databuss: data, msg:'获取成功', status:1});
            }
        });
    })
    // 全选
    route.post('/checkAll', (req, res)=> {
        var mobj = {}
        for (var i in req.body) {
            mobj = JSON.parse(i)
        }
        let sql = `update goods_cart set flag = ${mobj.flag} where user_id = ${mobj.user_id}`
        db.query(sql, (err,data) => {
            if(err) return res.send({msg:'请联系管理员', status:506}).end()
            res.send({database: data,msg:'获取成功', status:1})
        })
    })
    // 删除
    route.get('/deletes', (req, res)=> {
        var query1 = req.query.id
        console.log('query', query1)
        let sql = `delete from goods_cart where cart_id=${query1}`
        db.query(sql, (err, data)=> {
            if (err) res.send({msg:'请联系管理员', status:506}).end()
            res.send({dattebase:data,msg:'删除成功',status:1})
        })
    })
    // 获取历史记录
    route.post('/historys', (req,res)=> {
        var mObj ={}
        for (let obj in req.body) {
            mObj = JSON.parse(obj);
        }
        let sql =`select * from product where user_id='${mObj.uid}' and history=1`
        db.query(sql, (err,data)=> {
            if (err) res.send({msg:'请联系管理员', status:506}).end()
            res.send({database:data,msg:'获取成功', status:1})
        })
    })
    // 新增历史记录
    route.post('/histories',(req,res)=> {
        var mObj ={}
        for (let obj in req.body) {
            mObj = JSON.parse(obj);
        }
        let sql =`update product set history = ${mObj.history},user_id = ${mObj.user_id} where product_id = ${mObj.pruduc}`
        db.query(sql, (err, data)=> {
            if (err) res.send({msg:"请联系管理员", status:506}).end()
            res.send({database:data,msg:'获取成功', status:1})
        })
    })
    // 获取用户基本信息
    route.get('/userImg', (req, res) => {
        let sql = `select * from user`
        db.query(sql,(err,data)=> {
            if (err) res.send({msg:'请联系管理员', status:506}).end()
            res.send({database: data,msg:'请求成功', status:1})
        })
    })
    // 修改密码
    route.post('/passwd', (req, res)=> {
        var mObj ={}
        for (let obj in req.body) {
            mObj = JSON.parse(obj);
        }
        let pwd = mObj.commits
        let id = mObj.id
        bcrypt.hash(pwd, saltRounds, (err, pwd1) => {
        if (err) return res.send({msg:'注册用户失败',status:507})
        pwd = pwd1
        let sql =`update user set login_password = "${pwd}" where user_id = "${id}"`
        db.query(sql, (err,data)=> {
            if (err) return res.send({msg:'请联系管理员', status:506}).end()
                res.send({msg:'修改成功', status:1})
            })
        })
    })
    route.post('/goodadd', (req, res) => {
        var mObj ={}
        for (let obj in req.body) {
            mObj = JSON.parse(obj);
        }
        let sql = `update goods_cart set flag = ${mObj.flag},user_id = ${mObj.user_id} where product_id = ${mObj.pruduc}`
        db.query(sql ,(err,data)=> {
            if (err) return res.send({msg:'请联系管理员', status: 506}).end()
            res.send({database: data, msg:'获取成功', status:1})
        })
    })
    route.post('/addCarts', (req, res) => {
        let mObj = {};
        for (let obj in req.body) {
            mObj = JSON.parse(obj);
        }
        console.log('ids', mObj)
        let sql =`INSERT into goods_cart(product_id,user_id,goods_num,focusf_lag) values (${mObj.pruduct},${mObj.user_id}, 1,0)`
        db.query(sql, (err, data) => {
            if (err) {
                res.send({msg:'添加失败', status:506}).end()
            } else {
                console.log('data', data)
                res.send({bussdata:data,msg:'添加成功', status: 1})
            }
        })
    })
    route.post('/focusadd', (req, res) => {
        var mObj = {}
        for (let obj in req.body) {
            mObj = JSON.parse(obj)
        }
        let sql =`update product set focusf_lag = ${mObj.focus},user_id = ${mObj.user_id} where shop_id = ${mObj.pruduct}`
        db.query(sql, (err, data) => {
            if (err) return res.send({msg:'请联系管理员', status:506}).end()
            res.send({database: data, msg:'关注成功', status:1})
        })
    })
    route.post('/focus', (req, res) => {
        var mObj = {}
        for (let obj in req.body) {
            mObj = JSON.parse(obj)
        }
        let sql = `select * from product where user_id='${mObj.uid}' and focusf_lag=${mObj.focus}`
        db.query(sql, (err, data)=> {
            if (err) res.send({msg:'请联系管理员', status:506}).end()
            res.send({database: data,msg:'获取成功', status:1})
        })
    })
    route.post('/minusGoods', (req,res)=> {
        var mObj ={}
        for (let obj in req.body) {
            mObj = JSON.parse(obj)
        }
        let sql =`update goods_cart set goods_num = ${mObj.nums},user_id = ${mObj.user_id} where product_id = ${mObj.pruduc}`
        db.query(sql, (err, data) => {
            if (err) {
                res.send({msg:'请联系管理员', status:506}).end()
            } else {
                res.send({bussdata:data,msg:'添加成功', status: 1})
            }
        })
    })
    route.post('/search', (req, res) => {
        var mObj ={}
        for (let obj in req.body) {
            mObj = JSON.parse(obj)
        }
        let keyWord = mObj.kw;
        let hot = mObj.hot;
        let priceUp = mObj.priceUp;
        let priceDown = mObj.priceDown;
        const keywordStr1 = `select  *  from product,shop where product.shop_id=shop.shop_id and product.product_name`;
        const keywordStr = `select  *  from product,shop where product.shop_id=shop.shop_id and product.product_name like '%${keyWord}%'`;
        const hotStr = `select  *  from product,shop where product.shop_id=shop.shop_id and product.product_name like '%${keyWord}%' order by product_comment_num desc`;
        const priceUpStr = `select  *  from product,shop where product.shop_id=shop.shop_id and product.product_name like '%${keyWord}%' order by product_uprice asc`;
        const priceDownStr = `select  *  from product,shop where product.shop_id=shop.shop_id and product.product_name like '%${keyWord}%' order by product_uprice desc`;
        if (keyWord != '') {
            if (hot != '') {
                getSearchDatas(hotStr, res);
            } else if (priceUp != '') {
                getSearchDatas(priceUpStr, res);
            } else if (priceDown != '') {
                getSearchDatas(priceDownStr, res);
            } else {
                getSearchDatas(keywordStr, res);
            }
        } else {
            getSearchDatas(keywordStr1, res)
        }

    });
    /**
        get search datas
    */
    function getSearchDatas(keywordStr, res) {
        db.query(keywordStr, (err, data) => {
            if (err) return res.send({msg:'请联系管理员', status:506}).end()
            res.send({database:data,msg:'获取成功', status:1})
        });
    }
    /*
     *user reg func
     */
    route.post('/reg', (req, res) => {

        let mObj = {};
        for (let obj in req.body) {
            mObj = JSON.parse(obj);
        }
        let regName = mObj.regName;
        let regPasswd = mObj.regPasswd;
        const selectUser = `SELECT * FROM user where user_name='${regName}'`;
        bcrypt.hash(regPasswd, saltRounds, (err, pwd1) => {
            if (err) return res.send({msg:'注册用户失败',status:507})
            regPasswd = pwd1
            db.query(selectUser,(err,data1)=> {
                console.log('data1', data1[0].user_name)
                if (err) return res.send({msg:'服务器出错，请联系管理员', status: 504}).end()
                if (data1[0].user_name === regName) return res.send({msg:'用户已经注册过了', status: 506}).end()
                const insUserInfo = `INSERT INTO user(user_name,login_password,user_number) VALUES('${regName}','${regPasswd}','${regName}')`;
                delReg(insUserInfo, res);
            })
        })
        
    });
    /*
     *deal user register
     */
    function delReg(insUserInfo, res) {
        db.query(insUserInfo, (err) => {
            if (err) {
                res.send({ 'msg': '服务器出错', 'status': 0 }).end();
            } else {
                res.send({ 'msg': '注册成功', 'status': 1 }).end();
            }
        })
    }
    route.post('/login', (req, res) => {

        let mObj = {};
        for (let obj in req.body) {
            mObj = JSON.parse(obj);
        }
        let username = mObj.loginName;
        let password = mObj.loginPawd
        const selectUser = `SELECT * FROM user where user_name='${username}'`;
        db.query(selectUser, (err, data) => {
            if (err) {
                res.send({ 'msg': '服务器出错', 'status': 0 }).end();
            } else {
                if (data.length == 0) {
                    res.send({ 'msg': '该用户不存在', 'status': -1 }).end();
                } else {
                    let dataw = data[0];
                    console.log('dataw', dataw)
                    //login sucess
                    // if (dataw.login_password === password) {
                    //     //save the session 
                    //     req.session['user_id'] = dataw.user_id;
                    //     dataw.msg = "登录成功";
                    //     dataw.status = 1;
                    //     res.send(dataw).end();
                    // } else {
                    //     res.send({ 'msg': '密码不正确', 'status': -2 }).end();
                    // }
                    bcrypt.compare(password, dataw.login_password, (err, pwd1) => {
                        console.log('pwq', pwd1)
                        if (err) return res.send({msg:'登录失败',status:507})
                        if (!pwd1) return res.send({msg:'登录失败',status:508})
                        res.send({database: dataw, msg: '登录成功', status: 200 })
                    })
                }
            }
        });

    });
    route.get('/userinfo', (req, res) => {
        let uId = req.query.uId;
        const getU = `SELECT user_name,user_number FROM user where user_id='${uId}'`;
        db.query(getU, (err, data) => {
            if (err) {
                console.log(err);
                res.send({msg:'请联系管理员', status:506}).end()
            } else {
                res.send({database: data[0],status:1,msg:'获取成功'})
            }
        });
    });
    return route;
}
